#include "UART.h"

void USART_Init(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);    // 使能GPIO时钟
    rcu_periph_clock_enable(RCU_USART0);   // 使能串口时钟
	
	gpio_af_set(GPIOA, GPIO_AF_7, GPIO_PIN_9 | GPIO_PIN_10);				//配置端口复用

	//PA9 == TxD
	gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_9);  		//端口类型配置为复用
    gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);  

	//PA10 == RxD，官方的是GPIO_PUPD_PULLUP，我的是GPIO_PUPD_NONE
	gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_10);  	//端口类型配置为复用	
	gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_10);  

	//串口参数配置，官方的是115200
    usart_deinit(USART0);    						// 串口复位
//    usart_word_length_set(USART0, USART_WL_8BIT);   // 字长为8位
//    usart_stop_bit_set(USART0, USART_STB_1BIT);     // 停止位1位
//    usart_parity_config(USART0, USART_PM_NONE);		// 无校验
    usart_baudrate_set(USART0, 115200U);     		// 波特率9600
	
    usart_receive_config(USART0, USART_RECEIVE_ENABLE);     // 接收使能
	usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);   // 发送使能
    usart_enable(USART0);          							// 串口使能

	usart_hardware_flow_rts_config(USART0, USART_RTS_DISABLE);
    usart_hardware_flow_cts_config(USART0, USART_CTS_DISABLE);
	
	nvic_irq_enable(USART0_IRQn, 0, 0);
	usart_interrupt_enable(USART0, USART_INT_RBNE);
}

//buf是数据存储的指针，len是数据长度
void USART0_SendData(uint16_t *buf,uint16_t len)
{
     uint16_t t;
     for(t=0;t<len;t++)
     {
         while(usart_flag_get(USART0, USART_FLAG_TC) == RESET);  //等待发送
         usart_data_transmit(USART0,buf[t]);
     }
     while(usart_flag_get(USART0, USART_FLAG_TC) == RESET);    //等待发送完成   
}

int fputc(int ch, FILE *f)	//用这个就可以使用printf来打印，就不用SendData
{
    usart_data_transmit(USART0, (uint8_t)ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    return ch;
}

uint8_t Rec_Data;
uint8_t Count = 0;
uint8_t Rec_Flag;
uint8_t Rec_Buff[20];
uint16_t TIM1_CNT;
void USART0_IRQHandler(void)
{
    if(RESET != usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE))
	{
		timer_counter_value_config(TIMER1, 0);
		Rec_Flag = 1;
		Rec_Data = usart_data_receive(USART0);
		Rec_Buff[Count] = Rec_Data;
		Count ++;
		usart_interrupt_flag_clear(USART0, USART_INT_FLAG_RBNE);
    }
}

void UART_Rec_Pro(void)
{
	TIM1_CNT = timer_counter_read(TIMER1);
	if(Rec_Flag == 1)
	{
		if(TIM1_CNT >= 2)
		{
			if (Rec_Buff[0] == 'a' && Rec_Buff[1] == 'b' && Count == 2)
			{
				LED1_ON();
				printf("LED1_ON(ab)\r\n");
			}
			else if(Rec_Buff[0] == 'c' && Rec_Buff[1] == 'd' && Count == 2)
			{
				LED1_OFF();
				printf("LED1_OFF(cd)\r\n");
			}
			else
			{
				printf("Error");
			}
			Rec_Flag = 0;
			for(int i = 0; i < Count; i ++)
				Rec_Buff[i] = 0;
			Count = 0;
		}
	}
}
